package com.farm.sfile.wdas.util;

import java.io.File;
import java.rmi.RemoteException;
import java.util.List;

import org.apache.log4j.Logger;
import org.json.JSONException;

import com.farm.parameter.FarmParameterService;
import com.farm.sfile.domain.FileBase;
import com.farm.sfile.service.FileBaseServiceInter;
import com.farm.sfile.wdas.util.WSFileHttpUploads.ProgressHandle;
import com.farm.util.spring.BeanFactory;

public class WsServer {

	private static final Logger log = Logger.getLogger(WsServer.class);
	private static FileBaseServiceInter fileBaseServiceImpl = (FileBaseServiceInter) BeanFactory
			.getBean("fileBaseServiceImpl");
	private static boolean isRun = false;
	private static boolean continueRun = false;

	/**
	 * 从数据库取出数据并执行上传
	 */
	public static void doUpdataFiles() {
		if (!isRun) {
			log.info("WDAPS:上传服务启动...");
			// 未执行
			isRun = true;
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						upload();
					} finally {
						isRun = false;
					}
				}
			}) {
			}.start();
		} else {
			// 执行中
			continueRun = true;
			log.info("WDAPS:上传服务执行中，完成后将再次启动...");
		}
	}

	private static void upload() {
		continueRun = true;
		while (continueRun) {
			log.info("WDAPS:上传服务加载数据中...");
			try {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
				List<FileBase> files = fileBaseServiceImpl.getReadyRemoteLoadFiles();
				log.info("WDAPS:加载数据" + files.size() + "条");
				int n = 0;
				for (final FileBase file : files) {
					try {
						log.info("WDAPS:文件就绪(" + (++n) + "/" + files.size() + ")");
						WSClient apiClient = WSClient.getInstance(
								FarmParameterService.getInstance().getParameter("config.wdas.userid"),
								FarmParameterService.getInstance().getParameter("config.wdas.password"),
								FarmParameterService.getInstance().getParameter("config.wdas.secret"),
								FarmParameterService.getInstance().getParameter("config.wdas.url"));
						String filepath = fileBaseServiceImpl.getFileRealPath(file.getId());
						apiClient.uploadFile(new File(filepath), file.getTitle(), file.getId(), file.getId(),
								new ProgressHandle() {
									@Override
									public void handle(int percent, long allsize, long completesize, String state) {
										log.info("WDAPS:上传文件数据" + file.getTitle() + ":" + percent + "%");
									}
								});
						int filenum = apiClient.getFilenum(file.getId());
						fileBaseServiceImpl.completeRemoteLoad(file.getId(), filenum);
						log.info("WDAPS:文件完成上传");
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				log.info("WDAPS:本次数据处理完成");
			} finally {
				continueRun = false;
			}
		}
	}

	/**
	 * 获得远程播放地址
	 * 
	 * @param fileAppid
	 * @return
	 */
	public static String getPlayUrl(String fileid) {
		try {
			if (FarmParameterService.getInstance().getParameter("config.wdas.able").toLowerCase().equals("true")) {
				FileBase filebase = fileBaseServiceImpl.getFilebaseEntity(fileid);
				if (filebase.getLoadnum() > 0 && filebase.getLoadstate().equals("2")) {
					try {
						WSClient apiClient = WSClient.getInstance(
								FarmParameterService.getInstance().getParameter("config.wdas.userid"),
								FarmParameterService.getInstance().getParameter("config.wdas.password"),
								FarmParameterService.getInstance().getParameter("config.wdas.secret"),
								FarmParameterService.getInstance().getParameter("config.wdas.url"));
						String url = apiClient.getFilePlayUrl(fileid);
						if (url != null) {
							log.info("WDAPS:加载远程播放地址:" + url);
						}
						return url;
					} catch (RemoteException e) {
						log.error(e);
					} catch (JSONException e) {
						log.error(e);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getViewUrl(String fileid) {
		try {
			if (FarmParameterService.getInstance().getParameter("config.wdas.able").toLowerCase().equals("true")) {
				FileBase filebase = fileBaseServiceImpl.getFilebaseEntity(fileid);
				if (filebase.getLoadnum() > 0 && filebase.getLoadstate().equals("2")) {
					try {
						WSClient apiClient = WSClient.getInstance(
								FarmParameterService.getInstance().getParameter("config.wdas.userid"),
								FarmParameterService.getInstance().getParameter("config.wdas.password"),
								FarmParameterService.getInstance().getParameter("config.wdas.secret"),
								FarmParameterService.getInstance().getParameter("config.wdas.url"));
						String url = apiClient.getFileViewUrl(fileid);
						if (url != null) {
							log.info("WDAPS:加载远程预览地址:" + url);
						}
						return url;
					} catch (RemoteException e) {
						log.error(e);
					} catch (JSONException e) {
						log.error(e);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void delRemoteFile(String fileId) {
		try {
			if (FarmParameterService.getInstance().getParameter("config.wdas.able").toLowerCase().equals("true")) {
				try {
					WSClient apiClient = WSClient.getInstance(
							FarmParameterService.getInstance().getParameter("config.wdas.userid"),
							FarmParameterService.getInstance().getParameter("config.wdas.password"),
							FarmParameterService.getInstance().getParameter("config.wdas.secret"),
							FarmParameterService.getInstance().getParameter("config.wdas.url"));
					apiClient.delFile(fileId);
					log.info("WDAPS:删除远程文件副本");
				} catch (RemoteException e) {
					log.error(e);
				} catch (JSONException e) {
					log.error(e);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
